// ==UserScript==....................................
// @name             TexAgs Extension
// @namespace        texags
// @description      Version 2.00
// @include          http://texags.com/main/*
// @include          http://www.texags.com/main/*
// @include          http://mybcs.com/*
// @include          http://www.mybcs.com/*
// ==/UserScript==

// Credit to all the TexAgers that started work on this script. I didn't write
// all of this code myself. I started with a solid base and attempted to modify
// the script and clean it up a bit to make it easier to customize/read.
//
// --Fuzzbutt


/*******************************************************************************
**                                                                            **
**                        Global Variables                                    **
**                                                                            **
*******************************************************************************/


var testReply = /postreply/;
var testPost = /posttopic/;
var testEdit = /replyedit/;
var testTopic = /forum.topic/;
var testThread = /forum.reply/;

var maxImgSize = 1000;
var sigChecked = false;
var pageNumberThreshold = 4;
var numRepliesPerPage = 35;
var maxPageNumbers = 8;

var watchListHighlightColor = '770022';
var postedHighlightColor = '33ff33';
var repliedHighlightColor = '3333ff';
var sipOrange = '#c27334';

var userWatchList = Array(
   'WatchOle',
   'Liucci',
   'JeremyK',
   'MWR Admin',
   'Moderator',
   'ooshwa',
   'myBCS.com',
   'thisladyisacop',
   'Mr. Traffic',
   'Olin Buchanan',
   'gabe_bock',
   'Lauren Santacroce',
   'Trent Hunter',
   'Brice Jones',
   'TexAgs Studios',
   'Logan Lee',
   'Hunter Goodwin',
   'Seth McKinney',
   'Jerrod Johnson',
   'Coach Sherrill',
   'Ronnie Woodard'
   );

var sipList = Array(
   '2005Horn',
   '33',
   '91 Horn',
   '94 Texas EX',
   'A Corda',
   'AkersN',
   'AlexNguyen',
   'austx',
   'Authentic Horn',
   'awinlonghorn',
   'bassale47',
   'BleedOrange10',
   'booleyHorn',
   'BoyNamedSue',
   'Chest Rockwell',
   'Devinp23',
   'Dr Drunkenstein',
   'Fast Times',
   'FtWorthHorn',
   'Full Tilt',
   'FWHORN',
   'gnglonghorn',
   'GoHorns94',
   'h264',
   'Hellraiser97',
   'horn1',
   'Hornblood',
   'Hornographer',
   'Horns11',
   'hookem3',
   'huisache',
   'IgnatiusReilly',
   'IIIHorn',
   'INIGO MONTOYA',
   'Jakovasaur',
   'jefford22',
   'jkavvytx',
   'JTaylor',
   'KidTwist',
   'l-horndev',
   'landman1',
   'Lifeguard NO.2',
   'Lhorn01',
   'LHorns3',
   'locohorn',
   'LonghornsNo1',
   'Lost Saucer',
   'MidnightBevo',
   'Mister Randy Watson',
   'Mr. Drummond',
   'MustangOrange',
   'nbbob',
   'NerveEndings',
   'Nonhostile Sip',
   'northernhorn',
   'Norwegian Wood',
   'ObjectiveUTLAW91',
   'onehorn',
   'Pato',
   'Professor Terguson',
   'realhorn',
   'rscharnell',
   'saltwater',
   'Samsill98',
   'Skihorn',
   'sodiumacetate',
   'TEXAS FIGHT!',
   'Tex Pete',
   'Texas velvet maestro',
   'Texas_Fan',
   'Texas75',
   'TexasBorn',
   'TexasEx1994',
   'Texdoc',
   'The Lat Man',
   'Theo',
   'THorns90',
   'toucan82',
   'UniHorn',
   'UTGrad02',
   'UTLawHorn',
   'W.E. Henley',
   'West Horn',
   'Winston Wolfe',
   '@Texas.edu',
   'Nowhere Man',
   'omaha28',
   'MarcusT',
   'Longhorn Nation',
   'Nedley Mandingo',
   'TexasBB',
   'Gameover',
   'Bevolution',
   'Mailinator1892',
   'LonghornDub',
   'squid',
   'highwayman',
   'johnnyyou',
   'FXST',
   'UT2005',
   'hornsfan568',
   '20Horn09',
   'OrangeRout',
   'Hookem123',
   'Rob Lowe',
   'Texasfan1224',
   'horninatx',
   'sugarlandbevo',
   'RVHorn',
   'UTex09',
   '13 0 National Champs',
   'texasfight68',
   'Dwayne Hoover',
   'turk333',
   'BDog',
   'TheBeeve'
   );

var cubList = Array(
   'Hurin',
   'LonghornDub',
   'Big Old Bear'
   );

var theifList = Array(
   'PlanoGuy',
   'Godfather',
   'soonerborn'
   );

var tardList = Array(
   '0raider0',
   'Big 12-0',
   'BillJack',
   'BreakPoint778',
   'Cowtown Raider',
   'Cowtown Red',
   'DrKennethNoisewater',
   'Hong Kong Paul',
   'leachfan',
   'PaleHorse',
   'raiderjay',
   'rockylarues',
   'shiner raider',
   'TechDiver',
   'Techsan_02',
   'TechTard',
   'TENBOLLS',
   'Texas Tech Universe',
   'ttechguy',
   'TTechDeck',
   'TTUClint',
   'WreckemTXTech',
   'Zorro',
   'BonniePrinceBilly',
   'MHBT_Raider',
   'TheGoddess',
   'Dr.K',
   'Preferred Stock',
   'Raider15',
   'Matador05',
   'TTPointMan',
   'sexaT Tech',
   'redraiderzuke'
   );

var kSipTagImageSrc =
   '' +
   'JwdC3kM23qcmsf8SicMKih8DAwL6ZYriQU7aMWbGEQat7M6p4LqZyJKVuGaBpFpd1TIlgKXxd' +
   'N3xQEnRSKAAAAMDAwAAAACH5BAEAAB4ALAAAAAAbABQAQAXMoCeOZGmeYkNZ1yIQAAQBl/ECz' +
   'MVe2Klgm6BwOMQoUB5EIxKhOJ9QZwRxilhYD4ABN6sBYLnLZdNDms+ewnK1u0RoYvH1GimUnC' +
   'wJbMCACGoLbnBiGyUFGHGJcQaBiWR2aJGSkycFCApLTJqaDQqQJ0pNbBcVEHFzFhRGJgpNeRA' +
   'VOhEXEhMQEzpXFw0lrjUGEgsyNAYGLX9xGSUYugkLFQcGMxbFLQNxG8okDW0TTaSzjN/YvCUK' +
   'FIqJtdgbGkcoahgcREIcGA2flJEhADs=';

var kCubTagImageSrc =
   '' +
   'EQVR42mNgGAW0BI9uXP//8Vr3/3drGEjCID0gTLRFMA2kWkSyhdsmM/6f0gLEzQxwPBmIby5i' +
   '+P92NQQv6ICITYbKP1oGEb8wDyE2q5Xh/5O12v/x+gjkMgZHTCzowfB/fgfE5dcWoso9WQ4RB' +
   '1mILH57jtR/UHTgtmw1A9zCy/MRQfN8JUQM5EOYGIiPLRiNwlGDFKtlYAU4LHsBtWzbZNIsA6' +
   'sj1TKDMIb/KoFohlDTMmyYqpa9xeGz16sgYmVldLAMJhachsp/tBzTMud4IiwDpRxcll1dABF' +
   'b1IlqGbagRRbDmRpBEmv6cMfXrimoBsOyA754xZnPIEHJSHYxhY6frNUhXGRRwyKSC2OaFsLD' +
   'CgAAqWbSuLT4+tQAAAAASUVORK5CYII%3D';

//credit to crewez of TexAgs for creating the tard tag image
var kTardTagImageSrc =
   '' +
   'HAM5lYPrw8K4XD7oHALknIOiysN2TkL02MMOSgpxJO6sHAM2zqOXY1vbh4OKjoNrIwMUNBsJJ' +
   'P6oGAIQJAbEIAP///////yH5BAEAAB8ALAAAAAAhABQAAAX/4CeOZGmeaKqubOtWGBVpdG3fE' +
   'VWp2KxlAGAwQwQMiUgNBtX7ZTrQDgOBmECn1WgnI6GYKrPnoqDtIMrnDsQQ1exIlJ85wNYyyv' +
   'eOwBPdREoRTwgDFgoPHQQGBgQdCRcODwsPBhd8HRsbEiVyHQsXFQMBCgQPHqEeDgEXFgEWfAi' +
   'YCyVEUXQdAwUCBB4ColAeCR0Fr5gcJRJatgkeFg68th28t8QcsiQaUGe2BocDz3UKAY18Exsc' +
   'miQRl1Z7DxcKDoUB0MsGCh6w5n8kFRKYEwgKJJhQgECDAQMaQIgygMACAcUkvIGTAZPFfwjuY' +
   'LxDxdw5LycoSOBAsiSHAyhLFqI8YLKLCjAjTcqcKSHCRBc4c+o0EQIAOw==';

var kThiefTagImageSrc =
   '' +
   'EQVR42u2Uz0uUQRjH/TP0EN0ED106SHiRqLCiSBDCCjx0CMGjCN76YQTtIqa7JUWBdQmR1oM/' +
   '8c1DbYfoUEs/1FBYrUOx7mosuu/MvG98e57xB+/GzLgduogDDzPvzDzzeb/P88xUVR20/9m+L' +
   'cxj/k0as08e4XlXJwZaLpTZ4KWLeHy1TRuP2VK3buDt6Auwb8UghrAjH5o4XK+tv6UZuZUVlE' +
   'ol+L4PSf3sQP/uetT4B/iMikCs5O8DctkshCBIKBFKCREqbKyvYTp21wi8fu6sVukMnQnEJoW' +
   'AJMjOd29dPYIwRJGApv07Cq0h5fzYHBkU0uFRGH+X8gWrD9vUvT4zbKij3eokhKIQBog3nUCg' +
   'fm8pUwrFQgFeMomF9GujX8/lVjOs7/wZh7IAitTFm04iCJSGKeqLa3l49xMEe2X1NcJc4ZBCk' +
   'pJQV2VAxRE/fYqgAT5OTuDlgyS+UmGZ/Fprqs2wm3SQDfZuZFjnTUhFCimkFMLM5Lhee59KWc' +
   'NoVfbMkTO2jOdhU21V5c/l7O78Z5o3wXoOHbHnjCvHBWN72HaFYKps7tOMZ1VmrUa+E/wnLli' +
   'McuUTbH01h1/5VV2N/sYmZgYTxkp0Pl1862PHGpzAsTu3sZz5gO9zX/BjaRHpp0NloeP+2vFG' +
   '9wsSBXKx6JhvOxvvUGStbEyKKgJFQ8rxZsfu2qN75pL38F72+adXf1+0P9r9685J7fk5AAAAA' +
   'ElFTkSuQmCC';

var kUrlImageSrc =
   '' +
   'oAA8AAAJCjI+pywkPo5y0PmOzrnj73X0iFV7RAQSQqppgu0ptx8avjKc6i3qlfnJhYLDMD5Ea' +
   'xoi+4uiZhEqj0+ev+mpot40CADs=';

var kImgImageSrc =
   '' +
   'oAA8AAAJHjI+pyzkPo5y0PmOzrnj73X0iFV5YAKHDkXYIqUbqica1FMPTvPbOXCvJcpdi0dY7' +
   'ZoQsJHLlYu2Io6qwOrpiP9otqAEOgwsAOw==';

var kQuoteImageSrc =
   '' +
   'oAA8AAAJGjI+pyzkPo5y0PmOzrnj73X0iFULHZV6dg0jlEKQxOsMpSta4Xcf9DXsFXbLi7peb' +
   'nFS9UvMl3I0y0emnagXpsqKG9/stAAA7';

var kEmailImageSrc =
   '' +
   'oAA8AAAJHjI+pyzkPo5y0PmOzrnj73X0iFV7HEEAp2p2rVaIRRqvXncWnnPYI/uIEZbbba4XU' +
   '6Fy2I8sXUw1H1ChVZL16slpl4wv+FgAAOw==';

var kBoldImageSrc =
   '' +
   'TAA8AAAImjI+Zw+3PDJxOUmovzA1NHnVbMIIR+aCD2rGnubraOY91Ks/KvhcAOw==';

var kItalicImageSrc =
   '' +
   'TAA8AAAIjjI+Zw+3PDJxOUmovzJU3/2EBJpITOBznqG1s28EPqim2XQAAOw==';

var kNextArrowImageSrc =
   ''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AAAAAAAAAA' +
   'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
   'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
   'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAMAAAYALAAAAAAMAAwAAAhCAA0IG' +
   'EiwoMACCBMqHFiAgMOHDgcwfBgAokQBDQkEqPjwYsONICt61BhS5ESSFk9qTIkRIssCA2LKlC' +
   'lAYMGbBgICADs=';

//Unused Tags that we might want to use later

var kTShirtSipTag =
   '' +
   'EQVR42tWUy08TURTG+WeUR2s7JSq+gnGBC02MC3XtogkLdxaNhDRtpy0SlCYqC1Ex8VEfUYzE' +
   'akhMIfIQqjBlWgZqbUuLKHTRFhBN03bm885UaoulDlIXnuTLzcz9zvndc+/cqagoEdH5eTU78' +
   'hoT/S8QmQ2glNc/NQmfhynpyQXrGsJw7130d5vh7GjEIH0c7/UHwbXshK+lFiPGI3DeouGbdB' +
   'UUHOq5gQGbVvIyLfsxbDyK/staqc5bxwN4mbHCBXhHnehr3I65C9sQ1Vdiia7BinUHEYUlogT' +
   'RskWFBX01uHPVcOnUGNNpMNmkRLi5CjGTgsxTkn+F+JZoBalThcD5SoyfrUHU9ewXcHrMCZYk' +
   'rrZqELdoECsi8X2CaFks2Erha2t2TFiL50h+MrdsViLl7smDkc7cTQqSrCYmSjJuBJWrbA2Kd' +
   'K1EsgDmGsA7nQpxsxord04jw38H0pm/BiUB8MIqEve1WDQo8Y3J28ZPQR+GrpzBjO0E/BcbED' +
   'bvwwJdi5QAJHnIhqQgICmkpdyweS+pdRjejlOIcW8KP5LPkRCC7hHMDDwB+7gd7ksn8cVUK20' +
   'FYWZD4JEfgjiTSeWexTNaNFHwtB3DhN1Kaj1FiB3983VgHrYhbNotba24ap5PY6MQeEHyiLA5' +
   'g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exKj' +
   'qMll+dPEh9vggEN8SdmUZy1SAClMEQOl1sj8JK7sCrBnTxukjc4wJTlfhiewh+PYZnLnuFORD' +
   'pbR8sItDwBqufBygtJmCpFt9YGlY+96KhSVBRTmu1IcdEEHvEDPSTSTgnXhpS4/byKTPGmFN0' +
   '4LNvF3UGR3gtrHPciUiALgsYcI1j6E1z/Cxh320LQlqL2X4Da25TSbRZiXomiQkG3fjE17TPI' +
   '7PAk7laQUKBaHLQNp1BfsgXA1Vb4xOUgjx6J9HsQsiAW8sXzSTgsPcmPttGIkuc669Sgi1rL1' +
   'cB3UB8cxZDOR1SEi9jLHSKoIFqQmEgqBYRWJzNh8x6yOqCmHNwdTgwDcV9EnojzcMO5GtmIWC' +
   '7MTn0JjfpqOtNDKY+0RCc3pSrbiiyVLXkPPNmpms2SjFm4K79iZnwg5kHbsFlzimlz01hlV4C' +
   'vTTIIYVAHOywikEkTSB+ZyIW34ukIFrOveYn8aUmlNckV3e+jqdWMoWRgMrtbrZlTaoWL1oMP' +
   '0zZh+n0EY1fECeqUeE6pJsiqjp3v5iBkOTynBHMFF42SyJcko55WIJT9invGw0pxaSPRV3pws' +
   '/kj4ntscVObMve2cAiVD0aH/HnbOxb7RcW421ezRdpA2Hv1HBxZxBETBafN4kkxSuDiG2dQjr' +
   '8AUUNwm1cbtPAiDN0K8tv88c20xrnEiZnl3piE+TNq4xE+8EjGySEb33Fq9phUEjaijMOSXBL' +
   'fzCBlhIIko5MUTE9hIPr+MK2v9cfBp20hjVzibPePbG8Ow/roSiy8ArBdehT7eTF8Ov0s68xk' +
   'fGN8igBjGRFmp5GbnyFzchKG7cII0gWlLYT8o9+MnkZxP9vQPO2i9SHeL86YEEHTL8N7E8oXb' +
   'Om/XH8CnzDhujSvTQIAAAAASUVORK5CYII%3D';

if(
   testReply.test(window.location.href)
   || testPost.test(window.location.href)
   || testEdit.test(window.location.href)
   )
{
   handleReplyEdit();
}
else if ( testTopic.test(window.location.href) )
{
//   chrome.storage.sync.clear();

   chrome.storage.sync.get(
      [  "st_watchListColor",
         "st_postedColor",
         "st_startedColor",
         "st_watchListArray"
      ],
      function(result)
      {
         if(   !result["st_watchListColor"]
            || !result["st_postedColor"]
            || !result["st_startedColor"]
            || !result["st_watchListArray"]
            )
         {
            restoreDefault(result);
         }

         handleThreadList(result);
      }
   );

}
else if ( testThread.test(window.location.href) )
{
   handleInsideThread();
}

/*******************************************************************************
**                                                                            **
**                 Replying, Posting, Editing, or PMing                       **
**                                                                            **
*******************************************************************************/
function handleReplyEdit()
{
   var allInputs;

   allInputs = document.evaluate(
      "//input[@type='checkbox']",
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
      );

   if( ! testEdit.test(window.location.href) )
   {
      //resize replies that have emoticons
      var textareas = document.getElementsByName('body');
      if(textareas)
      {
         var textarea = textareas[0];
         textarea.cols = 54;
      }
   }

   //check for the signature button to be checked. Do we want this option?
   //signatures are really annoying as it is
   for (var j = 0; j < allInputs.snapshotLength; j++)
   {
      allInputs.snapshotItem(j).checked = sigChecked;
   }

   if (testReply.test(window.location.href))
   {
      var url = window.location.href;
      var findTopicID = /topic_id=(\d+)/;
      url.match(findTopicID);
      var topicID = RegExp.$1;
      var submitSpan = getElementsByClass("inlinewordbuttons",null,"span");
      submitSpan[0].childNodes[0].childNodes[0].addEventListener(
         'click',
         function(event)
            {
               if(null == localStorage.getItem(topicID))
               {
                  localStorage.setItem(topicID, 'none');
               }
            },
         false
         );
   }

   var headings = getElementsByClass("formlabel", null, "td");

   var reply = /Your/;

   for (var i = 0; i < headings.length; i++)
   {
      if (reply.test(headings[i].innerHTML))
      {
         var textareas = document.getElementsByTagName('textarea');

         var textarea = textareas[0];
         headings[i].insertBefore(
            document.createElement('br'),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            document.createElement('br'),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            createButton(
               kUrlImageSrc,
               'url'
               ),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            document.createElement('br'),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            createButton(
               kImgImageSrc,
               'img'
               ),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            document.createElement('br'),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            createButton(
               kQuoteImageSrc,
               'quote'
               ),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            document.createElement('br'),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            createButton(
               kEmailImageSrc,
               'email'
               ),
            headings[i].lastChild.nextSibling
         );

         headings[i].insertBefore(
            document.createElement('br'),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            createButton(
               kBoldImageSrc,
               'b'
               ),
            headings[i].lastChild.nextSibling
            );

         headings[i].insertBefore(
            createButton(
               kItalicImageSrc,
               'i'
               ),
            headings[i].lastChild.nextSibling
            );
      }
   }
}


/*******************************************************************************
**                                                                            **
**                      List of Threads in Board                              **
**                                                                            **
*******************************************************************************/
function handleThreadList(a_Options)
{
   //the footer is a DIV class that contains the username
   var theFooter = getElementsByClass("footer2");

   //extract the username from the footer
   var myUserName = theFooter[0].childNodes[1].innerHTML;

   //get a list of the topics
   var topics = getElementsByClass("topics", null, "a");
   var findTopicID = /topic_id=(\d+)/;
   var thisTopic, topicID, lastReplyCount, currentReplyCount;

   var l_watchListArray = JSON.parse( a_Options["st_watchListArray"] );

   //loop through all of the topics
   for (i=0; i<topics.length;i++)
   {
      thisTopic = topics[i];

      //check to see if the number of pages is sufficient to display the
      //number of pages on the list of the threads.
      if (pageNumberThreshold
         && childNodeList(thisTopic)[4].innerHTML
            > ((pageNumberThreshold - 1) * numRepliesPerPage - 1))
      {
         thisTopic.style.paddingRight = 25;
         var forumID = /(&forum_id=\d+)$/;

         var numberOfPages = Math.ceil(
            ( childNodeList(thisTopic)[4].innerHTML / numRepliesPerPage )
            + 1 / numRepliesPerPage
            );

         for (var j = 1; j <= numberOfPages; j++)
         {
            if (numberOfPages > maxPageNumbers && j
               == Math.floor(maxPageNumbers/2)+1)
            {
               thisTopic.parentNode.insertBefore(
                  document.createTextNode("..."),
                  thisTopic.parentNode.lastChild.nextSibling
                  );

               j = (numberOfPages - Math.ceil(maxPageNumbers/2) + 1);
            }

            var pageLink = document.createElement('a');

            if (j==1)
            {
               pageLink.href = thisTopic.href;
            }
            else
            {
               pageLink.href =
                  thisTopic.href.replace(forumID, "&page="+j+"$1");
            }

            pageLink.setAttribute('class', 'topics');
            pageLink.style.padding = 2;
            pageLink.innerHTML = j;

            thisTopic.parentNode.insertBefore(
               pageLink,
               thisTopic.parentNode.lastChild.nextSibling
               );
         }
      }

      //search for the topic ID and store it in topicID below
      thisTopic.href.match(findTopicID);
      //this will store the first match from the previous search in topicID
      topicID = RegExp.$1;

      //get the lastReplyCount from the local storage to see if it needs
      //to be updated
      lastReplyCount = localStorage.getItem(topicID);

      //if this is the first time to see this specific topic
      if (lastReplyCount == null)
      {
         colorList(l_watchListArray, thisTopic, '#'+a_Options["st_watchListColor"]);

         //check to see if I started the topic
         if (childNodeList(thisTopic)[3].innerHTML
            == myUserName)
         {
            //set the color and properties for of the node's children
            for(j=0;j<childNodeList(thisTopic).length; j++)
            {

               setNodeColor(
                  childNodeList(thisTopic)[j],
                  '#'+a_Options["st_startedColor"]
                  );

               setFontWeight(
                  childNodeList(thisTopic)[j],
                  'bold'
                  );
            }

            //if I posted this topic, store it
            localStorage.setItem(
               topicID,
               childNodeList(thisTopic)[4].innerHTML
               );
         }
      }
      else //if we've already stored this topic
      {
         var bgColor;

         //figure out if it should be the posted highlight color or the
         //replied highlight color
         if (childNodeList(thisTopic)[3].innerHTML
            == myUserName)
         {
            bgColor = '#'+a_Options["st_startedColor"];
         }
         else
         {
            bgColor = '#'+a_Options["st_postedColor"];
         }

         //set the color for that node to whatever we decided above
         for(j=0;j<childNodeList(thisTopic).length; j++)
         {
            childNodeList(thisTopic)[j].style.backgroundColor = bgColor;
            childNodeList(thisTopic)[j].style.fontWeight = 'bold';
         }

         //set the reply count number
         //TODO: should we check to see if we're the last one to post on this
         //and reset it?
         currentReplyCount = childNodeList(thisTopic)[4].innerHTML;

         if (lastReplyCount == 'none')
         {
            localStorage.setItem(topicID,currentReplyCount);
         }
         else
         {
            if (currentReplyCount != lastReplyCount)
            {
               childNodeList(thisTopic)[4].innerHTML =
                  lastReplyCount +
                  " <font color='red'>+" +
                  (currentReplyCount-lastReplyCount) +
                  "</font>";

               localStorage.setItem(topicID,currentReplyCount);
            }
         }
      }
   }
}


/*******************************************************************************
**                                                                            **
**                         Inside Thread                                      **
**                                                                            **
*******************************************************************************/

function handleInsideThread()
{
   var thisAnchor, userLevelImg, userName;

   //get all <a name> anchors in the document
   var allAnchors = document.evaluate(
      '//a[@name]',
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
      );

   for (var i = 0; i < allAnchors.snapshotLength; i++)
   {
      thisAnchor = allAnchors.snapshotItem(i);

      //there may be some fake <a name> anchors that don't correspond to the
      //username. If we come across one we don't need to do anything
      if( null == thisAnchor.parentNode.nextSibling )
      {
         continue;
      }

      userLevelImg =
         thisAnchor.parentNode.nextSibling.childNodes[1].childNodes[0];

      userName = thisAnchor.childNodes[0].innerHTML.toUpperCase();

      //go through each list and check to see if it is any of the lists
      for (var j = 0; j < sipList.length; j++)
      {
         if (sipList[j].toUpperCase() == userName)
         {
            //insert the sip tag before the user level image
            insertImageBefore(kSipTagImageSrc,userLevelImg);
         }
      }

      for (var k = 0; k < cubList.length; k++)
      {
         if (cubList[k].toUpperCase() == userName)
         {
            insertImageBefore(kCubTagImageSrc,userLevelImg);
         }
      }

      for (var k = 0; k < tardList.length; k++) {
         if (tardList[k].toUpperCase() == userName)
         {
            insertImageBefore(kTardTagImageSrc,userLevelImg);
         }
      }

      for (var k = 0; k < theifList.length; k++) {
         if (theifList[k].toUpperCase() == userName)
         {
            insertImageBefore(kThiefTagImageSrc,userLevelImg);
         }
      }

   }


   //get all of the img tags in the document
   var allImages = document.getElementsByTagName('img');

   //resize images that are too large
   for (i=0; i < allImages.length; i++)
   {
      if(allImages[i].width > maxImgSize)
      {
         allImages[i].width = maxImgSize;
      }
   }

   var pageNumber, lastPage;
   var testPageNumbers = /Page:/;
   var findPageNumber = /\s(\d+)\s/;

   //get all of the divisions that are "mediumboxtitle". Some of these elements
   //store the page numbers, but only if page numbers are listed
   var pageNumbers = getElementsByClass("mediumboxtitle", null, "div");

   for(i=0;i<pageNumbers.length;i++)
   {
      //test to see if this is one of the elements that store the page number
      if (testPageNumbers.test(pageNumbers[i].innerHTML))
      {
         //find the current page number
         pageNumbers[i].innerHTML.match(findPageNumber);
         pageNumber = RegExp.$1;

         //find what the last page in the list is
         lastPage = (pageNumbers[i].childNodes.length+1)/2;

         //if we're not the last page then insert the next image
         if (pageNumber < lastPage)
         {
            var nextPage = document.createElement('a');
            nextPage.href = pageNumbers[i].childNodes[pageNumber*2-1].href;
            pageNumbers[i].insertBefore(nextPage, pageNumbers[i].lastChild.nextSibling);
            var nextArrow = document.createElement('img');
            nextArrow.src = kNextArrowImageSrc;
            nextPage.insertBefore(nextArrow, nextPage.firstChild);
         }

         //if we're not the first page then insert the previous image
         if (pageNumber > 1) {
            var prevPage = document.createElement('a');
            prevPage.href = pageNumbers[i].childNodes[pageNumber*2-3].href;
            pageNumbers[i].insertBefore(prevPage, pageNumbers[i].firstChild);
            var prevArrow = document.createElement('img');
            prevArrow.src = kPrevArrowImageSrc;
            prevArrow.style.paddingRight = 3;
            prevPage.insertBefore(prevArrow, prevPage.firstChild);
         }
      }
   }
}




/*******************************************************************************
**                                                                            **
**                         Options Page                                       **
**                                                                            **
*******************************************************************************/



// Saves options
function save_options()
{
   var dataObj = {};

   dataObj["st_watchListColor"] =
      document.getElementById("watchlist_color").value;

   dataObj["st_postedColor"] =
      document.getElementById("posted_color").value;

   dataObj["st_startedColor"] =
      document.getElementById("started_color").value;

   chrome.storage.sync.set(dataObj);

   // Update status to let user know options were saved.
//   var status = document.getElementById("status");
//   status.innerHTML = "Options Saved.";
//   setTimeout(function() { status.innerHTML = "";}, 2000);
}

//This function gets the current watchlist value and fills it into the text box.
//It should only be called from the options page.
function fillWatchListTextBox()
{
   chrome.storage.sync.get(
      ["st_watchListArray"],
      function(result)
      {
         if( !result["st_watchListArray"] )
         {
            restoreDefault(result);
         }

         _fillWatchListTextBox( JSON.parse( result["st_watchListArray"] ) );
      }
   );
}

// fills the textbox on the options page with the default value of the list and
// sets the local variable for the list or sets the text box with the current
// value of the watch list
function _fillWatchListTextBox(a_watchListArray)
{
   var l_multipleSelect = document.getElementById("watchlist_selector");

   //we have to have the proper text box to continue. We really should never
   //hit this unless the html file is changed
   if(  null == l_multipleSelect )
   {
      return;
   }

   //check the local variable to see if we should load the default
   if ( localStorage.ls_restoreDefault == undefined ||
      localStorage.ls_restoreDefault != "false"
      )
   {
      //reload the default watchlist into the local storage
      loadDefaultWatchList();
   }

   //clear the list
   while(l_multipleSelect.options.length > 0)
   {
      l_multipleSelect.remove(0);
   }

   for( i=0; i < a_watchListArray.length; i++)
   {
      var l_option = new Option;
      l_option.text = a_watchListArray[i];
      l_option.value = i;
      l_multipleSelect.options[i] = l_option;
   }
}

// restores the default watchlist to the
function restoreDefault(a_result)
{
   localStorage.ls_restoreDefault = "true";
   loadDefaultWatchList();

   localStorage.ls_watchListColor = watchListHighlightColor;

   var dataObj = {};

   dataObj["st_watchListColor"] = watchListHighlightColor;

   dataObj["st_postedColor"] = postedHighlightColor;

   dataObj["st_startedColor"] = repliedHighlightColor;

   dataObj["st_watchListArray"] = JSON.stringify(userWatchList);

   chrome.storage.sync.set(dataObj);

   a_result["st_watchListColor"] = watchListHighlightColor;

   a_result["st_postedColor"] = postedHighlightColor;

   a_result["st_startedColor"] = repliedHighlightColor;

   a_result["st_watchListArray"] = dataObj["st_watchListArray"];
}

//adds an item to the user
function addToUserWatchlist()
{
   var l_textBox = document.getElementById("user_name");
   //load the array from the local storage and parse it.
   var l_watchListArray = JSON.parse(localStorage.ls_watchListArray);

   //we have to have the proper text box to continue. We really should never
   //hit this unless the html file is changed
   if(  null == l_textBox )
   {
      return;
   }

   //remove the white space from the textbox value
   var l_trimmedText = l_textBox.value.trim();

   //check for duplicates
   for( i=0; i < l_watchListArray.length; i++)
   {
      if( l_trimmedText == l_watchListArray[i] )
      {
         l_textBox.value = "";
         return;
      }
   }

   l_watchListArray.push(l_trimmedText);

   var dataObj = {};

   dataObj["st_watchListArray"] = JSON.stringify(l_watchListArray);

   chrome.storage.sync.set(dataObj);

   fillWatchListTextBox();

   l_textBox.value = "";
}

//removes the selected item(s) from the list
function removeFromList()
{
   //load the array from the local storage and parse it.
   var l_watchListArray = JSON.parse(localStorage.ls_watchListArray);

   var l_multipleSelect = document.getElementById("watchlist_selector");

   //we have to have the proper text box to continue. We really should never
   //hit this unless the html file is changed
   if( null == l_multipleSelect )
   {
      return;
   }

   //check to see if something is selected
   if( -1 == l_multipleSelect.selectedIndex )
   {
      return;
   }

   //for some reason we are out of sync
   if( l_multipleSelect.options.length != l_watchListArray.length )
   {
      return;
   }

   //search for selected items
   for( i=l_multipleSelect.options.length-1; i>=0; i--)
   {
      if( true == l_multipleSelect.options[i].selected )
      {
         l_watchListArray.splice(i,1);
      }
   }

   var dataObj = {};

   dataObj["st_watchListArray"] = JSON.stringify(l_watchListArray);

   chrome.storage.sync.set(dataObj);

   fillWatchListTextBox();

   l_multipleSelect.selectedIndex = -1;

}

//restore options for the options page.
function restore_options()
{
   chrome.storage.sync.get(
      [  "st_watchListColor",
         "st_postedColor",
         "st_startedColor",
         "st_watchListArray"
      ],
      function(result)
      {
         if(   !result["st_watchListColor"]
            || !result["st_postedColor"]
            || !result["st_startedColor"]
            || !result["st_watchListArray"]
            )
         {
            restoreDefault(result);
         }

         //restore the textbox values
         fillWatchListTextBox( JSON.parse( result["st_watchListArray"] ) );

         //restore the color values
         document.getElementById('watchlist_color').color.fromString(
            String( result["st_watchListColor"] )
            );

         document.getElementById('posted_color').color.fromString(
            String( result["st_postedColor"] )
            );

         document.getElementById('started_color').color.fromString(
            String( result["st_startedColor"] )
            );
      }
   );

}

/*******************************************************************************
**                                                                            **
**                       Helper Functions                                     **
**                                                                            **
*******************************************************************************/

//this function gets the elements by class name in a node or throughout the
//document
//
// searchClass       class to search for. This parameter is required
// node              node to search in. If null, the entire document will
//                      be searched
// tag               tag to look for within the node or document. If null, all
//                      tags will be searched
// return            array of elements found
function getElementsByClass(searchClass,node,tag)
{

   var classElements = new Array();

   //if Node is NULL search the entire document
   if ( node == null )
   {
      node = document;
   }

   //if the tag is null search for everything
   if ( tag == null )
   {
      tag = '*';
   }

   //get everything in the node with the tag name
   var els = node.getElementsByTagName(tag);

   //set the pattern to search for the beginning of the string or a white space
   //followed by the search class followed by a whitespace or the end of the
   //string
   var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");

   //loop through each element and see if the className matches the search class
   //if it does then add it to the array
   for (i = 0, j = 0; i < els.length; i++)
   {
      if ( pattern.test(els[i].className) )
      {
         classElements[j] = els[i];
         j++;
      }
   }

   return classElements;
}

//This is a function that handles the event of a click. This function inserts
//the information into the text box for a reply, edit or a PM
//
// event             event that occured
function insertAtCursor(event)
{
   event.preventDefault();
   var link, textarea, openTag, closeTag;
   link = event.currentTarget;
   openTag = '['+link.title+']';
   closeTag = '[/'+link.title+']';
   var textareas = document.getElementsByTagName('textarea');
   textarea = textareas[0];
   var scrollX = textarea.scrollLeft;
   var scrollY = textarea.scrollTop;
   if (textarea.selectionStart || textarea.selectionStart == '0')
   {
      var startPos = textarea.selectionStart;
      var endPos = textarea.selectionEnd;
      textarea.value = textarea.value.substring(0, startPos)
         + openTag
         + textarea.value.substring(
            textarea.selectionStart,
            textarea.selectionEnd
            )
         + closeTag
         + textarea.value.substring(
            endPos,
            textarea.value.length
            );

      if (startPos == endPos)
      {
         textarea.selectionStart = endPos + openTag.length;
      }
      else
      {
         textarea.selectionStart = endPos + openTag.length + closeTag.length;
      }

      textarea.selectionEnd = textarea.selectionStart;
   }

   textarea.focus();
   textarea.scrollLeft = scrollX;
   textarea.scrollTop = scrollY;
}

//This function creates the buttons in the reply, edit, or PM window. The button
//that is created will connect to an event that inserts it into the textArea
//
// imageSource       source file or data for the image.
// title             what title the button should have. This will be inserted
//                   in the text area when the button is selected
// return            the created button
function createButton(imageSource,title)
{
   var image, button;
   image = document.createElement('img');
   image.src =  imageSource;
   image.style.backgroundColor = '#5a121e';
   image.style.marginTop = 2;
   image.style.marginLeft = 2;

   image.addEventListener(
      'mouseover',
      function (event)
         {
            this.style.backgroundColor = '#000000';
         },
      false
      );

   image.addEventListener(
      'mouseout',
      function (event)
         {
            this.style.backgroundColor = '#5a121e';
         },
      false
      );

   button = document.createElement('a');
   button.title = title;
   button.href = title;
   button.addEventListener('click', insertAtCursor, false);
   button.appendChild(image);
   return button;
}

//this is a helper function to set the node color for the background and border
//
// node              node to color
// color             color to set the node to
function setNodeColor(node, color)
{
   node.style.backgroundColor = color;
   node.style.borderColor = color;
}

//this is a helper function to set the font weight of a node
//
// node              node to set the font weight
// fw                font weight to set
function setFontWeight(node, fw)
{
   node.style.fontWeight = fw;
}

//this is a helper function to insert an image before a location
//
// imgSrc            source file or data to use as image
// loc               location to insert before
function insertImageBefore(imgSrc, loc)
{
   var myImg = document.createElement('img');
   myImg.src = imgSrc;

   loc.parentNode.insertBefore(myImg, loc.nextSibling);
}

//This function gets the child node list from the grandparent node. This was
//simply a very common operation so this function simplifys the code a bit
//
// node              node to get the child node list from the grandparent node
// return            grandparent node's child node list
function childNodeList(node)
{
   return node.parentNode.parentNode.childNodes;
}

//This function sets the color for a watchlist.
//
// list              list to search for a match
// node              node to match against
// color             color to set in the case of a match
function colorList(list, node, color)
{
   //go through the list
   for(j=0; j<list.length; j++)
   {
      //make sure to set the names to uppercase so we aren't case sensitive
      if ( list[j].toUpperCase() ==
         childNodeList(node)[3].innerHTML.toUpperCase())
      {
         for(k=0; k < childNodeList(node).length; k++)
         {
            setNodeColor(
               childNodeList(node)[k],
               color
               );

            setFontWeight(
               childNodeList(node)[k],
               'bold'
               );
         }
      }
   }
}

//This function will restore the default list
function loadDefaultWatchList()
{
   localStorage.ls_watchListArray = JSON.stringify(userWatchList);
   localStorage.ls_restoreDefault = "false";
}
